package com.zzzzzz.account.signin;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.PasswordMatcher;
import org.apache.shiro.authc.credential.PasswordService;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import com.zzzzzz.account.user.User;
import com.zzzzzz.account.user.UserDao;

public class ShiroDbRealm extends AuthorizingRealm {

	@Resource
	private UserDao userDao;
	@Resource
	private PasswordMatcher passwordMatcher;
	@Resource
	private PasswordService passwordService;
	
	@PostConstruct
	public void initCredentialsMatcher() {
		setName("shiroDbRealm");
		passwordMatcher.setPasswordService(passwordService);
		setCredentialsMatcher(passwordMatcher);
	}
	
	@Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
        User user = userDao.findByEmail(token.getUsername());
		if(user != null) {
			if(user.getStatus() == 1){
				throw new UserActiveException();
			}else{
				return new SimpleAuthenticationInfo(user.getUserId(), user.getPassword(), getName());
			}
        }
		return null;
    }

	@Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		return info;
    }

	
}
